﻿using IdentityServer4.Stores;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Models;
using IdentityServer4.EntityFramework.DbContexts;
using Microsoft.EntityFrameworkCore;
using IdentityServer4.EntityFramework.Mappers;

namespace ZhongJia.Lock.Web.Extensions
{
    public class PersistedGrantStore : IPersistedGrantStore
    {
        private readonly PersistedGrantDbContext _dbContext;
        public PersistedGrantStore(PersistedGrantDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public async Task<IEnumerable<PersistedGrant>> GetAllAsync(string subjectId)
        {
            return (await _dbContext.PersistedGrants.Where(p => p.SubjectId == subjectId).ToListAsync()).Select(c => c.ToModel());
        }

        public async Task<PersistedGrant> GetAsync(string key)
        {
            return (await _dbContext.PersistedGrants.FirstOrDefaultAsync(p => p.Key == key))?.ToModel();
        }

        public async Task RemoveAllAsync(string subjectId, string clientId)
        {
            _dbContext.PersistedGrants.RemoveRange(_dbContext.PersistedGrants.Where(p => p.SubjectId == subjectId && p.ClientId == clientId));
            await _dbContext.SaveChangesAsync();
        }

        public async Task RemoveAllAsync(string subjectId, string clientId, string type)
        {
            _dbContext.PersistedGrants.RemoveRange(_dbContext.PersistedGrants.Where(p => p.SubjectId == subjectId && p.ClientId == clientId && p.Type == type));
            await _dbContext.SaveChangesAsync();
        }

        public async Task RemoveAsync(string key)
        {
            _dbContext.PersistedGrants.Remove(await _dbContext.PersistedGrants.FirstOrDefaultAsync(p => p.Key == key));
            await _dbContext.SaveChangesAsync();
        }

        public async Task StoreAsync(PersistedGrant grant)
        {
            _dbContext.PersistedGrants.Add(grant.ToEntity());
            await _dbContext.SaveChangesAsync();
        }
    }
}
